﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using DMS.BaseClass;
using DMS.Business.Utility;
using DMS.Business.Modules.Organization;
using System.Web.UI.HtmlControls;
using System.Data;

namespace DMS.Web.Common.Controls
{
    public partial class UserListJson : ListControlBase
    {
        #region 成员属性
        /// <summary>
        /// 当前部门ID
        /// </summary>
        public string ContextDeptID
        {
            get
            {
                return this.hidDeptID.Value;
            }
            set
            {
                this.hidDeptID.Value = value;
            }
        }
        /// <summary>
        /// 启用搜索
        /// </summary>
        public bool EnableSearch
        {
            get
            {
                return this.dvSearch.Visible;
            }
            set
            {
                this.dvSearch.Visible = value;
            }
        }
        /// <summary>
        /// 页大小限制
        /// </summary>
        public int PageLimte
        {
            get
            {
                return this.pager.PageSize;
            }
            set
            {
                this.pager.PageSize = value;
            }
        }
        private string _OnClientSelectBtnClick = string.Empty;
        public string OnClientSelectBtnClick
        {
            get
            {
                return this._OnClientSelectBtnClick;
            }
            set
            {
                this._OnClientSelectBtnClick = value;
            }
        }
        protected override List<Control> ControlSet
        {
            get
            {
                List<Control> ctrls = new List<Control>();
                ctrls.Add(this.imgSelectDept);

                return ctrls;
            }
        }
        protected override List<string> ControlSetInGrid
        {
            get
            {
                List<string> ctrlIds = new List<string>();

                return ctrlIds;
            }
        }
        protected override Dictionary<int, string> ColumnStateSettings
        {
            get
            {
                Dictionary<int, string> settings = new Dictionary<int, string>();
                foreach (ListItem item in this.lbGridColState.Items)
                {
                    try
                    {
                        int key = Convert.ToInt32(item.Text);
                        string value = item.Value;
                        settings.Add(key, value);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogException(ex);
                    }
                }

                return settings;
            }
        }
        protected override WebControl MainListControl
        {
            get
            {
                return this.dgUserList;
            }
        }
        #endregion

        #region 界面事件
        /// <summary>
        /// 控件加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.GetParams();

            if (!IsPostBack && !string.IsNullOrEmpty(this.ContextDeptID))
            {
                this.InitDataList();
            }
            if(!String.IsNullOrEmpty(Request.QueryString["mode"])){
                btnSync.Visible = false;
                expBtn.Visible = false;
            }
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dgUserList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
            {
                return;
            }

            User user = e.Item.DataItem as User;
            if (user == null)
            {
                return;
            }

            // 用户性别
            Label userSexCrtl = e.Item.FindControl("labUserSex") as Label;
            if (userSexCrtl != null)
            {
                switch (user.Sex)
                {
                    case SexTypes.Male:
                        userSexCrtl.Text = "男";
                        break;
                    case SexTypes.Female:
                        userSexCrtl.Text = "女";
                        break;
                    case SexTypes.Unknow:
                        userSexCrtl.Text = "未知";
                        break;
                    default:
                        userSexCrtl.Text = string.Empty;
                        break;
                }
                userSexCrtl.ToolTip = userSexCrtl.Text;
            }

            // 用户部门
            Label userDeptCtrl = e.Item.FindControl("labUserDept") as Label;
            Literal ltlDeptFullName = e.Item.FindControl("ltlDeptFullName") as Literal;
            Department userDept = user.Dept;
            if (userDeptCtrl != null && userDept != null)
            {
                userDeptCtrl.Text = userDept.Name;
                userDeptCtrl.ToolTip = userDept.FullName;
            }
            if (ltlDeptFullName != null && userDept != null)
            {
                ltlDeptFullName.Text = userDept.FullName;
            }

            HtmlAnchor lkSelectBtn = e.Item.FindControl("lkSelectBtn") as HtmlAnchor;
            if (lkSelectBtn != null && !string.IsNullOrEmpty(this._OnClientSelectBtnClick))
            {//选人界面                
                string script = this._OnClientSelectBtnClick;
                if (this._OnClientSelectBtnClick.Contains("%ActorType%"))
                {
                    script = script.Replace("%ActorType%", user.ActorType.ToString());
                }
                if (this._OnClientSelectBtnClick.Contains("%ID%"))
                {
                    script = script.Replace("%ID%", user.ID.ToString());
                }
                if (this._OnClientSelectBtnClick.Contains("%Name%"))
                {
                    script = script.Replace("%Name%", user.Name);
                }
                if (this._OnClientSelectBtnClick.Contains("%LoginID%"))
                {
                    script = script.Replace("%LoginID%", user.LoginID);
                }
                if (this._OnClientSelectBtnClick.Contains("%DeptFullName%") && user.Dept != null)
                {
                    script = script.Replace("%DeptFullName%", user.Dept.FullName);
                }
                if (this._OnClientSelectBtnClick.Contains("%DeptID%") && user.Dept != null)
                {
                    script = script.Replace("%DeptID%", user.Dept.ID.ToString());
                }
                if (this._OnClientSelectBtnClick.Contains("%DeptName%") && user.Dept != null)
                {
                    script = script.Replace("%DeptName%", user.Dept.Name);
                }
                if (this._OnClientSelectBtnClick.Contains("%Mobile%"))
                {
                    script = script.Replace("%Mobile%", user.Mobile);
                }
                lkSelectBtn.Attributes["onclick"] = string.Format("javascript:{0};", script);
            }
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pager_PageChanged(object sender, EventArgs e)
        {
            this.InitDataList();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            this.pager.GoToPage(1);
            this.InitDataList();
        }
        protected void btnSync_Click(object sender, EventArgs e)
        {
            try
            {
               
            }
            catch (Exception ex)
            {
                LogHelper.LogException(ex);
            }
        }

        public void BtnExp_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("姓名");
            dt.Columns.Add("登录帐号");
            dt.Columns.Add("性别");
            dt.Columns.Add("所属部门");
            dt.Columns.Add("移动电话");
            dt.TableName = "移动用户";

            DataRow r = null;
            int total = 0;
            string condition = string.Empty;

            Department dept = null;
            if (!string.IsNullOrEmpty(this.hidDeptID.Value))
            {
                dept = UserHelper.GetDepartmentByID(this.hidDeptID.Value);
            }
            if (dept == null)
            {
                List<Department> rootDepts = UserHelper.GetRootDepartments();
                if (rootDepts.Count > 0)
                {
                    dept = rootDepts[0];
                }
            }

            if (dept != null)
            {
                this.txtDeptName.Text = dept.Name;
                if (this.ddlContainSub.SelectedValue == "1")
                {
                    condition += string.Format(" AND [DeptIDPath] Like '{0}%'", dept.IDPath.ToString().ToUpper());
                }
                else
                {
                    condition += string.Format(" AND [DeptID] = '{0}'", dept.ID.ToString().ToUpper());
                }
            }
            if (!string.IsNullOrEmpty(this.txtUserName.Text))
            {
                condition += string.Format(" AND [UserName] LIKE '%{0}%'", (object) this.txtUserName.Text.Trim());
            }

            if (!string.IsNullOrEmpty(this.txtLoginID.Text))
            {
                condition += string.Format(" AND [LoginID] LIKE '%{0}%'", (object) this.txtLoginID.Text.Trim());
            }

            if (!string.IsNullOrEmpty(this.txtMobile.Text))
            {
                condition += string.Format(" AND [Mobile] LIKE '%{0}%'", (object) this.txtMobile.Text.Trim());
            }

            if (this.ddlSex.SelectedValue.ToLower() != "all")
            {
                condition += string.Format(" AND [Sex] = '{0}'", (object) this.ddlSex.SelectedValue);
            }

            if (this.ddlTempUser.SelectedValue == "0")
            {
                condition += string.Format(" AND [IsTmpUser] = '{0}'", (object) this.ddlTempUser.SelectedValue);
            }
            List<User> users = UserHelper.GetUsers(0, 0, out total, condition, null);
            foreach (User u in users)
            {
                r = dt.NewRow();
                r["姓名"] = u.Name;
                r["登录帐号"] = u.LoginID;
                switch (u.Sex)
                {
                    case SexTypes.Male:
                        r["性别"] = "男";
                        break;
                    case SexTypes.Female:
                        r["性别"] = "女";
                        break;
                    case SexTypes.Unknow:
                        r["性别"] = "未知";
                        break;
                    default:
                        r["性别"] = string.Empty;
                        break;
                }
                r["所属部门"] = u.Dept.FullName;
                r["移动电话"] = u.Mobile;
                dt.Rows.Add(r);
            }
            if (dt.Rows.Count == 0)
            {
                r = dt.NewRow();
                r["姓名"] = String.Empty;
                r["登录帐号"] = String.Empty;
                r["性别"] = string.Empty;
                r["所属部门"] = String.Empty;
                r["移动电话"] = String.Empty;
                dt.Rows.Add(r);
            }

            ClientHelper.Instance.ExportToExcel(dt, "移动用户");
        }
        #endregion

        #region 内部方法
        /// <summary>
        /// 获取参数
        /// </summary>
        private void GetParams()
        {
            // 部门ID
            Department dept = null;
            if (!IsPostBack && !string.IsNullOrEmpty(Request["DeptID"]))
            {
                try
                {
                    dept = UserHelper.GetDepartmentByID(Request["DeptID"].ToString());
                }
                catch (Exception ex)
                {
                    string code = LogHelper.LogException(ex);
                    string msg = string.Format("没法正常读取参数，请与管理员联系。\\r\\n错误码：", code);
                    ClientHelper.Instance.Alert(msg);
                }

                if (dept != null)
                {
                    this.hidDeptID.Value = dept.ID.ToString();
                    this.txtDeptName.Text = dept.Name;
                }
                else
                {
                    List<Department> rootDepts = UserHelper.GetRootDepartments();
                    if (rootDepts.Count > 0)
                    {
                        Department rootDept = rootDepts[0];
                        this.hidDeptID.Value = rootDept.ID.ToString();
                        this.txtDeptName.Text = rootDept.Name;
                    }
                }
            }

        }
        /// <summary>
        /// 初始化列表
        /// </summary>
        public void InitDataList()
        {
            int total = 0;
            string condition = string.Empty;

            Department dept = null;
            if (!string.IsNullOrEmpty(this.hidDeptID.Value))
            {
                dept = UserHelper.GetDepartmentByID(hidDeptID.Value);
            }
            if (dept == null)
            {
                List<Department> rootDepts = UserHelper.GetRootDepartments();
                if (rootDepts.Count > 0)
                {
                    dept = rootDepts[0];
                }
            }

            if (dept != null)
            {
                this.txtDeptName.Text = dept.Name;
                if (this.ddlContainSub.SelectedValue == "1")
                {
                    condition += string.Format(" AND [DeptIDPath] Like '{0}%'", dept.IDPath.ToString().ToUpper());
                }
                else
                {
                    condition += string.Format(" AND [DeptID] = '{0}'", dept.ID.ToString().ToUpper());
                }
            }
            if (!string.IsNullOrEmpty(this.txtUserName.Text))
            {
                condition += string.Format(" AND [UserName] LIKE '%{0}%'", (object) this.txtUserName.Text.Trim());
            }

            if (!string.IsNullOrEmpty(this.txtLoginID.Text))
            {
                condition += string.Format(" AND [LoginID] LIKE '%{0}%'", (object) this.txtLoginID.Text.Trim());
            }

            //if (!string.IsNullOrEmpty(this.txtPinYin.Text))
            //{
            //    condition += string.Format(" AND [PinYin] LIKE '%{0}%'", this.txtPinYin.Text.Trim());
            //}

            if (!string.IsNullOrEmpty(this.txtMobile.Text))
            {
                condition += string.Format(" AND [Mobile] LIKE '%{0}%'", (object) this.txtMobile.Text.Trim());
            }

            if (this.ddlSex.SelectedValue.ToLower() != "all")
            {
                condition += string.Format(" AND [Sex] = '{0}'", (object) this.ddlSex.SelectedValue);
            }

            if (this.ddlTempUser.SelectedValue == "0")
            {
                condition += string.Format(" AND [IsTmpUser] = '{0}'", (object) this.ddlTempUser.SelectedValue);
            }

            List<User> users = UserHelper.GetUsers(pager.PageSize, pager.CurrentPageIndex, out total, condition, null);
            this.dgUserList.DataSource = users;
            this.dgUserList.DataBind();

            this.pager.RecordCount = total;


            // 处理空数据
            if (total == 0)
            {
                this.dgUserList.Visible = false;
                this.pager.Visible = false;
                this.dvEmpty.Visible = true;
            }
            else
            {
                this.dgUserList.Visible = true;
                this.pager.Visible = true;
                this.dvEmpty.Visible = false;
            }
        }
        #endregion






    }
}